package com.ycorn.order.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value("${security.oauth2.resource.id}")
    private String resourceId;

    /**
     * 资源服务令牌解析服务
     * 使用远程服务请求授权服务器校验token,必须指定校验token 的url、client_id，client_secret
     *
     * @return
     */
//    @Bean
//    public ResourceServerTokenServices tokenService() {
//        RemoteTokenServices service = new RemoteTokenServices();
//        service.setCheckTokenEndpointUrl(checkTokenEndpointUrl);
//        service.setClientId(clientId);
//        service.setClientSecret(clientSecret);
//        return service;
//    }

    @Autowired
    private ResourceServerTokenServices tokenServices;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(resourceId) // 配置资源服务的资源Id
                .tokenServices(tokenServices)
                .stateless(true); // 配置无状态的
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('all')") // 配置http安全控制
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //  session无状态
    }
}